<?php


namespace app\index\controller;

use app\common\model\UserAddr;
use app\common\services\ConfirmReceipt;
use think\Response;
use think\response\Json;
use think\Validate;
use app\index\validate\Phone;
use think\Db;
use app\index\server\UserServer;
class User extends Base
{
    /**
     * 个人中心头部
     */
    public function index()
    {
        $data = [
            'id'=>$this->user['id'],
            'us_nickname' => $this->user['us_nickname'],
            'us_head_pic'=>$this->user['us_head_pic'],
            'us_type' =>$this->user['us_type']
        ];
        $this->s_msg('',$data);
    }

    /**
     * 我的团队
     */
    public function myTeam()
    {
        $id =$this->user['id'];
        // 统计推荐人类型及个数
        $data = model('user')->whereIn('us_pid',$id)->field('us_type')->select();
//        halt($data);
        foreach ($data as $k=>$v)
        {
            $data[$k] = $v['us_type'];
        }
//        $num_0 = 0;
        $num_1 = 0;
        $num_2 = 0;
        $num_3 = 0;
        foreach ($data as $k=>$v)
        {
//            if ($v == 0) {
//                $num_0 += 1;
//            }
            if ($v == 1) {
                $num_1 += 1;
            }
            if ($v == 2) {
                $num_2 += 1;
            }
            if ($v == 3) {
                $num_3 += 1;
            }
        }

        // 统计邀请人所获得的奖金
        $money = model('money_team')
            ->whereIn('us_id',$id)
            ->field('money')
            ->select();
        $money_num = 0;
        foreach ($money as $k=>$v)
        {
            $money_num += $money[$k]['money'];
        }
        $num  = ['member'=>$num_1,'shopowner'=>$num_2,'operate'=>$num_3];
        $data=['money'=>$money_num,'num'=>$num];
        $this->s_msg('',$data);
    }

    /**
     * 团队详情
     */
    public function teamDetails()
    {
        $id =$this->user['id'];
        $type = input('post.type');
        $page = input('post.page');
        $team = new UserServer;
        $data =$team->getTeam($id,$type,$page);
        return $data;
    }


    /**
     * 排名
     */
//    public function sort()
//    {
//        $paiming = db('config')->where('id',155)->value('value');
//        $start_time = date("Y-m-d H:i:s",strtotime("-$paiming day"));
//        $end_time = date("Y-m-d H:i:s");
//
//        // 所有会员id
//        $suo_id = model('user')->column('id');
//        foreach ($suo_id as $k=>$v){
//            $pid_num[] =  model('user')
//                ->where('us_pid',$v)
//                ->whereBetweenTime('us_add_time',$start_time,$end_time)
//                ->where('us_type', 2)
//                ->count();
//
////            $ids[$k]['num'] =db('User')
////                ->whereIn('us_pid', $v['id'])
////                ->whereBetweenTime('us_add_time',$start_time,$end_time)
////                ->where('us_type', 1)
////                ->count();
////            $ids[$k]['money'] = \db('wallet')->where('wallet_type',null)
////                ->where('us_id',$v['id'])->value('wa_num');
//        }
//
//        halt($pid_num);
//        $num = array();
//        foreach ($ids as $v) {
//            $num [] = $v['num'];
//        }
//        array_multisort($num, SORT_DESC, $ids);
//        return $this->s_msg('',$ids);
//
//
//
//
//
//
//
//        }

//        $aaaa = model('user')->whereIn('us_pid',)->
//        halt($suo_id);
//
//        $ids = db('user')->where('us_pid',$id)->field('id,us_tel,us_type,us_nickname')->select();
//        halt($ids);
//        $type = input('post.type');
//        if (empty($type)){
//            return $this->e_msg('参数不能为空');
//        }
//        if ($type==1){
//            foreach ($ids as $k=>$v)
//            {
//                $ids[$k]['num'] =db('User')
//                    ->whereIn('us_pid', $v['id'])
//                    ->whereBetweenTime('us_add_time',$start_time,$end_time)
//                    ->where('us_type', 1)
//                    ->count();
//                $ids[$k]['money'] = \db('wallet')->where('wallet_type',null)
//                    ->where('us_id',$v['id'])->value('wa_num');
//            }
//            $num = array();
//            foreach ($ids as $v) {
//                $num [] = $v['num'];
//            }
//            array_multisort($num, SORT_DESC, $ids);
//            return $this->s_msg('',$ids);
//        }
//        if ($type == 2){
//            foreach ($ids as $k=>$v)
//            {
//                $ids[$k]['num'] =db('User')
//                    ->whereIn('us_pid', $v['id'])
//                    ->whereBetweenTime('us_add_time',$start_time,$end_time)
//                    ->where('us_type', 2)
//                    ->count();
//                $ids[$k]['money'] = \db('wallet')->where('wallet_type',null)
//                    ->where('us_id',$v['id'])->sum('wa_num');
//            }
//            $num = array();
//            foreach ($ids as $v) {
//                $num [] = $v['num'];
//            }
//            array_multisort($num, SORT_DESC, $ids);
//            return $this->s_msg('',$ids);
//        }
//    }


    /**
     * 排名
     */
    public function sort()
    {
        $paiming = db('config')->where('id',155)->value('value');
        $start_time = date("Y-m-d H:i:s",strtotime("-$paiming day"));
        $end_time = date("Y-m-d H:i:s");

        $id = $this->user['id'];

        $ids = model('user')->where('us_pid',$id)->field('id,us_tel,us_type,us_nickname')->select();
        halt($ids);
        $type = input('post.type');
        if (empty($type)){
            return $this->e_msg('参数不能为空');
        }
        if ($type==1){
            foreach ($ids as $k=>$v)
            {
                $ids[$k]['num'] =db('User')
                    ->whereIn('us_pid', $v['id'])
                    ->whereBetweenTime('us_add_time',$start_time,$end_time)
                    ->where('us_type', 1)
                    ->count();
                $ids[$k]['money'] = \db('money_detailed')
                    ->where('type',2)
                    ->where('us_id',$v['id'])
                    ->sum('money');
            }
            $num = array();
            foreach ($ids as $v) {
                $num [] = $v['num'];
            }
            array_multisort($num, SORT_DESC, $ids);
           return $this->s_msg('',$ids);
        }
        if ($type == 2){
            foreach ($ids as $k=>$v)
            {
                $ids[$k]['num'] =db('User')
                    ->whereIn('us_pid', $v['id'])
                    ->whereBetweenTime('us_add_time',$start_time,$end_time)
                    ->where('us_type', 2)
                    ->count();
                $ids[$k]['money'] = \db('money_detailed')
                    ->where('type',2)
                    ->where('us_id',$v['id'])
                    ->sum('wa_num');
            }
            $num = array();
            foreach ($ids as $v) {
                $num [] = $v['num'];
            }
            array_multisort($num, SORT_DESC, $ids);
            return $this->s_msg('',$ids);
        }
    }


       /**
     *  修改手机号
     */
    public function editTel()
    {
        $id = $this->user['id'];
        $phone = input('post.phone');
        $code = input('post.code');
        $phones = ['phone'=>$phone];
        $check =  validate('Phone');
        $rel = $check->check($phones);
        if (!$rel){
          return  $this->e_msg($check->getError());
        }
        $select_tel = db('user')->where('us_tel',$phone)->select();
        if (count($select_tel)==0){

        	$code_info = cache($phone . 'code') ?: "";
            if (!$code_info) {
                $this->e_msg('请重新发送验证码');
            } elseif (trim(input('post.code')) != $code_info) {
                $this->e_msg('验证码不正确');
            }
            unset($code);
            $update = db('user')->where('id',$id)->update(['us_tel'=>$phone]);
            if ($update){
                return $this->s_msg('修改成功');
            }else{
                return $this->e_msg('并未做出修改');
            }

        }else{
            return $this->e_msg('账户已存在');
        }
    }


    private function getAllChildrenId($id)
    {
        $ids = $this->getChildrenId($id) ?? [];
        $noHandleIds = $ids;
        while (!empty($noHandleIds)) {
            $id = array_shift($noHandleIds);
            $childrenIds = $this->getChildrenId($id);
            foreach ($childrenIds as $v) {
                array_push($ids, $v);
                array_push($noHandleIds, $v);
            }
        }
        return $ids;
    }

    private function getChildrenId($id)
    {
        return db('user')
            ->where('us_pid', $id)
            ->column("id");
    }



    /**
     * 我的订单
     */
    public function myOrder()
    {
        $page = input('post.page');
        $id =$this->user['id'];
        $my_order['data'] = model('order')
            ->whereIn('us_id',$id)
            ->order('or_add_time desc')
            ->field('id,or_num,or_status')
            ->paginate(10, true, ['type' => 'bootstrap',
                'var_page' => 'page',
                'page' => $page]);
//        halt($my_order);
//            ->select();
        foreach ($my_order['data'] as $k=>$value)
        {
            $my_order['data'][$k]['order_detail'] = model('order_detail')
                ->whereIn('or_id',$value['id'])
                ->field('or_pd_head_pic,or_pd_name,or_pd_total,ca_id')
                ->find();
            $my_order[$k]['order_num'] = $value['or_num'];
            $my_order[$k]['order_status'] = $value['or_status'];

        }
        $xq_num = model('order')->whereIn('us_id',$id)->count();
        $tx_page_num = ceil($xq_num / 10);
        $my_order['xq_page'] = $tx_page_num;
        $data=[];


        $data['data']=$my_order['data'];
        $data['xq_page']=$my_order['xq_page'];



//        foreach ($data['data'] as $k=>$v){
//            $data['data']['xq'] =  $datas['xq_page'];
//        }
        $this->s_msg('',$data);

    }


    public function myOrders()
    {
//        $page = input('post.page');
        $id =$this->user['id'];
        $my_order = model('order')
            ->whereIn('us_id',$id)
            ->field('id,or_num,or_status')
            ->select();
//        halt($my_order);
        foreach ($my_order as $k=>$value)
        {
            $my_order[$k]['order_detail'] = model('order_detail')
                ->whereIn('or_id',$value['id'])
                ->field('or_pd_head_pic,or_pd_name,or_pd_total,ca_id')
                ->select();
//            $my_order[$k]['order_num'] = $value['or_num'];
//            $my_order[$k]['order_status'] = $value['or_status'];

        }
//        halt($my_order);
        $this->s_msg('',$my_order);

    }



    /**
     * 取消订单 查看物流
     */
    public function order()
    {
        $order_num = input('post.order_num');
        $id = $this->user['id'];
        $type = input('post.type');
        //取消订单
        if ($type == 1){
            if (empty($order_num)){
                $this->e_msg('订单号不能为空');
            }
            $id =$this->user['id'];
            $recall_order = db('order')->whereIn('us_id',$id)->where('or_num',$order_num)->update(['or_status' => 4]);
            if($recall_order){
                $this->s_msg('操作成功');
            }else{
                $this->e_msg('操作失败');
            }
        }elseif($type ==2){
            $list = db('order')
                ->where('or_num',$order_num)
                ->where('us_id',$id)
                ->field('or_express,or_express_num,deliver_time,or_remark')
                ->find();
            if($list){
                $this->s_msg('',$list);
            }else{
                $this->e_msg('无此物流号');
            }
        }else{
            $this->e_msg('参数错误');
        }
        //查看物流
//        if ($type ==2)

    }


    /**
     *  订单确认收获
     */
    public function collect()
    {
        $order_num = input('post.order_num');
        $data = ['or_status'=>3];
        $up = db('order')->where('or_num',$order_num)->update($data);
        $order_id = model('order')->where('or_num',$order_num)->value('id');
        // 金额重新调整
        $tz = new ConfirmReceipt();
        // 符合时间订单id
        $tz->index($order_id);
        if ($up){
            $this->s_msg('已收货');
        }else{
            $this->e_msg('无效参数');
        }

    }



    /**
     * 根据订单查询数据
     */
    public function listOrder()
    {
        $order_num = input('post.order_num');
        $addrId = input('post.addr_id');
        $id = $this->user['id'];
        if (empty($addrId)){
            $this->e_msg('收货地址不能为空');
        }
      db('order')->where('or_num',$order_num)->update(['addr_id'=>$addrId]);

        $order = model('order')
            ->where('or_num',$order_num)
            ->where('us_id',$id)
            ->value('id');

        $list_order = model('order_detail')
            ->where('or_id',$order)
            ->select();

        foreach ($list_order as $k=>$v){
            $goods[] = model('product')->where('id', $v['pd_id'])
                ->field('type,pd_name,pd_head_pic,pd_price')->find();
        }
        if($list_order ){
            $this->s_msg('',$goods);
        }else{
            $this->e_msg('订单无效');
        }
    }





    /**
     * 查看物流
     */
//    public function logistics(){
//        $or_num = input('post.or_num');
//        $id = $this->user['id'];
//        $list = db('order')
//            ->where('or_num',$or_num)
//            ->where('us_id',$id)
//            ->field('or_express,or_express_num,deliver_time,or_remark')
//            ->find();
//        if($list){
//            $this->s_msg('',$list);
//        }else{
//            $this->e_msg('无此物流号');
//        }
//    }

    /**
     * 更改登录密码
     */
    public function editPwd()
    {
        $id = $this->user['id'];
        $phone = input('post.phone');
        $code = input('post.code');
        $new = input('post.new');
        $type = input('post.type');
        $check = ['phone' => $phone];
        $validate = Validate('Phone');
        if (!$validate->check($check)) {
            $this->e_msg($validate->getError());
        }
        if (!$new) {
            $this->e_msg('请完善信息');
        }
        if ($type ==1){
            $data['us_pwd'] = encrypt($new);
            $code_info = cache($phone . 'code') ?: "";
            if (!$code_info) {
                $this->e_msg('请重新发送验证码');
            } elseif (trim(input('post.code')) != $code_info) {
                $this->e_msg('验证码不正确');
            }
            unset($code);
            $rel = model('User')->where('id',$id)->update($data);
            if($rel){
                $this->s_msg('密码修改成功');
            }else{
                $this->e_msg('密码并未修改');
            }
        }elseif ($type ==2){
            $data['us_pay_pwd'] = encrypt($new);
            $code_info = cache($phone . 'code') ?: "";
            if (!$code_info) {
                $this->e_msg('请重新发送验证码');
            } elseif (trim(input('post.code')) != $code_info) {
                $this->e_msg('验证码不正确');
            }
             unset($code);
            $rel = model('User')->where('id',$id)->update($data);
            if($rel){
                $this->s_msg('密码修改成功');
            }else{
                $this->e_msg('密码并未修改');
            }
        }else{
            $this->e_msg('参数错误');
        }


    }

    /**
     * 更改交易密码
     */
//    public function editPayPwd()
//    {
//        $id = $this->user['id'];
//        $phone = input('post.phone');
//        $new = input('post.new');
//
//        $check = ['phone' => $phone];
//        $validate = Validate('Phone');
//        if (!$validate->check($check)) {
//            $this->e_msg($validate->getError());
//        }
//        if (!$new) {
//            $this->e_msg('请完善信息');
//        }
//        $data['us_pay_pwd'] = encrypt($new);
//        $code_info = cache(input('post.mobile') . 'code') ?: "";
//        if (!$code_info) {
//            $this->e_msg('请重新发送验证码');
//        } elseif (trim(input('post.code')) != $code_info) {
//            $this->e_msg('验证码不正确');
//        }
//        $rel = model('User')->where('id',$id)->update($data);
//        if($rel){
//            $this->s_msg('密码修改成功');
//        }else{
//            $this->e_msg('密码并未修改');
//        }
//
//
//    }

  public function wx()
    {
        $id = $this->user['id'];
        $type = input('post.type');
        $tel = input('post.tel');
        $phone = input('post.phone');
        $data = ['phone' => $phone];
        $code = input('post.code');
        $validate = Validate('Phone');
        if (!$validate->check($data)) {
            $this->e_msg($validate->getError());
        }
        if ($type == 1) {
            $code_info = cache($phone . 'code') ?: "";
            if (!$code_info) {
                $this->e_msg('请重新发送验证码');
            } elseif (trim(input('post.code')) != $code_info) {
                $this->e_msg('验证码不正确');
            }
            unset($code);
            $data['we_account'] = $phone;
            $rel = Db::name('user')->where('id', $id)->update($data);
            if ($rel) {
                $this->s_msg('微信绑定成功');
            } else {
                $this->e_msg('微信并未做出修改');
            }
        } elseif ($type == 2) {
            $code_info = cache($phone . 'code') ?: "";

            if (!$code_info) {
                $this->e_msg('请重新发送验证码');
            } elseif (trim(input('post.code')) != $code_info) {
                $this->e_msg('验证码不正确');
            }
            unset($code);
            $data['ali_account'] = $phone;
            $rel = model('User')->where('id', $id)->update($data);
            if ($rel) {
                $this->s_msg('支付宝绑定成功');
            } else {
                $this->e_msg('支付宝并未做出修改');
            }
        } elseif ($type == 3) {
            $select_tel = db('user')->where('us_tel', $phone)->select();
            if (empty($select_tel)) {
            	  
               $code_info = cache($tel . 'code') ?: "";
    
              if (!$code_info) {
                  $this->e_msg('请重新发送验证码');
               } elseif (trim(input('post.code')) != $code_info) {
                  $this->e_msg('验证码不正确');
              }
            
               unset($code);
                $update = db('user')->where('id', $id)->update(['us_tel' => $phone]);
                if ($update) {
                    return $this->s_msg('修改成功');
                } else {
                    return $this->e_msg('并未做出修改');
                }
            } else {
                return $this->e_msg('账户已存在');
            }

        } else {
            $this->e_msg('参数错误');
        }

    }

    /**
     * 支付宝绑定
     */
//    public function ali()
//    {
//        $id = $this->user['id'];
//        $phone = input('post.phone');
//        $data = ['phone' => $phone];
//        $validate = Validate('Phone');
//        if (!$validate->check($data)) {
//            $this->e_msg($validate->getError());
//        }
//        $code_info = cache(input('post.mobile') . 'code') ?: "";
//        if (!$code_info) {
//            $this->e_msg('请重新发送验证码');
//        } elseif (trim(input('post.code')) != $code_info) {
//            $this->e_msg('验证码不正确');
//        }
//        $data['ali_account'] =$phone;
//        $rel = model('User')->where('id',$id)->update($data);
//        if($rel){
//            $this->s_msg('密码修改成功');
//        }else{
//            $this->e_msg('密码并未修改');
//        }
//
//    }


    /**
     * 申请成为运营中心
     */
    public function apply()
    {
        $id = $this->user['id'];
        $state =input('post.state');
        $money = input('post.money');
        $phone = input('post.phone');

        $data = ['phone' => $phone];
        $validate = Validate('Phone');
        if (!$validate->check($data)) {
            $this->e_msg($validate->getError());
        }
        $code_info = cache($phone . 'code') ?: "";
        if (!$code_info) {
            $this->e_msg('请重新发送验证码');
        } elseif (trim(input('post.code')) != $code_info) {
            $this->e_msg('验证码不正确');
        }
        unset($data['code']);
//        $data['us_tel'] =$phone;
        if ($state == 2){
            $data = [
                'us_id' => $id,
                'tx_num' => $money,
                'tx_apply_time' => date('Y-m-d H:i:s'),
                'tx_status' => 0,
                'tx_zhongxing'=>2,
                'tx_name'=>'驳回后在次申请'
            ];
            $rel = db('tixian')->insert($data);
            if ($rel) {
                $this->s_msg('已申请');
            }
        }
        //判断是否提交
       $zhongxing =  db('tixian')->where('us_id',$id)->where('tx_zhongxing',2)->find();
        if ($zhongxing){
            $this->e_msg('已提交申请');
        }
        //判断是否为运营中心
        $type = db('user')->where('id', $id)->value('us_type');
        if ($type == 3) {
            $this->e_msg('该账户已是运营中心，换个账户试试');
        } else {
            $data = [
                'us_id' => $id,
                'tx_num' => $money,
                'tx_apply_time' => date('Y-m-d H:i:s'),
                'tx_status' => 0,
                'tx_zhongxing'=>2,
                'tx_name'=>'申请运营中心'
            ];
            $rel = db('tixian')->insert($data);
            if ($rel) {
                $this->s_msg('已提交申请');
            }

        }


    }

    /**
     * 进入运营中心前判断状态
     */
    public function zxType(){
        $id = $this->user['id'];
//        halt($id);
        $type = db('user')->where('id', $id)->value('us_type');
//        halt($type);
        if ($type == 3) {
            $this->e_msg('该账户已是运营中心,换个账户试试');
        }

       $status =  db('tixian')
           ->where('us_id',$id)
           ->where('tx_zhongxing',2)
           ->column('tx_status','tx_apply_time');
        if (count($status)==0){
            $this->s_msg('可以申请');
        }
        if (count($status)>1){
            // 以时间为键进行排序
            ksort($status);
            //最后一次申请运营中心的状态
            $z_status = array_pop($status);
            if ($z_status == 0) {
                $this->e_msg('已再次提交申请', 4);
            } elseif ($z_status == 1) {
                $this->e_msg('已通过');
            } elseif ($z_status == 2) {
                $this->e_msg('已驳回', 3);
            }
//            else {
//                $this->s_msg('可以申请');
//            }
        }
        if (count($status) == 1) {
            foreach ($status as $k => $v) {
                if ($v == 0) {
                    $this->e_msg('已提交申请', 4);
                } elseif ($v == 1) {
                    $this->e_msg('已通过');
                } elseif ($v == 2) {
                    $this->e_msg('已驳回', 3);
                } else {
                    $this->s_msg('可以申请');
                }
            }
        }

    }

    /**
     * 新闻信息
     */
    public function news()
    {
        $list = model('news')->where('type','=','0')
            ->field('id,title,add_time,pic')
            ->select();
        if($list) {
            $this->s_msg('成功',$list);
        }
    }

    /**
     * 新闻详情
     */
    public function newsNews()
    {
        $id =input('post.id');
        $list = db('news')->where('id',$id)->find();
        if($list) {
            $this->s_msg('成功',$list);
        }
    }


    /**
     * 更改密码公共方法
     * @param $phone  手机号
     * @param $new    新密码
     * @param $data   更新的数据
     */
    private function edit($phone,$mobile,$new,$data){
        $id = $this->user['id'];
//        $phone = input('post.phone');
//        $new = input('post.new');

        $check = ['phone' => $phone];
        $validate = Validate('Phone');
        if (!$validate->check($check)) {
            $this->e_msg($validate->getError());
        }
        if (!$new) {
            $this->e_msg('请完善信息');
        }
//        $code_info = cache(input('post.mobile') . 'code') ?: "";
       $code_info = cache(input('post.mobile') . 'code') ?: "";
        if (!$code_info) {
            $this->e_msg('请重新发送验证码');
        } elseif (trim(input('post.code')) != $code_info) {
            $this->e_msg('验证码不正确');
        }
        $rel = model('User')->where('id',$id)->update($data);
        if($rel){
            $this->s_msg('密码修改成功');
        }else{
            $this->e_msg('密码并未修改');
        }
    }



    /**
     * 退出登录
     */
    public function exitLogin(){
        $tel = input('post.tel');
        if (empty($tel)){
            $this->e_msg('无账号',2,'');
        }
        if (is_array($tel)){
            foreach ($tel as $k=>$v){
                $data[] = \db('user')
                    ->where('us_tel',$v)
                    ->field('us_all_get,us_nickname,us_tel')->find();
            }
        }else{
            $this->e_msg('参数错误');
        }

        $this->s_msg('',$data);



    }



}